package com.minyifang.wcspf.work.ui.user.fragments;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.minyifang.wcspf.R;
import com.minyifang.wcspf.common.base.BaseMvpFragment;
import com.minyifang.wcspf.common.utils.ImageUtils;
import com.minyifang.wcspf.common.utils.ToastHelper;
import com.minyifang.wcspf.common.widgets.CustomDialog;
import com.minyifang.wcspf.work.event.RefreshEvent;
import com.minyifang.wcspf.work.ui.goods.activities.ChoosePayTypeActivity;
import com.minyifang.wcspf.work.ui.home.activities.MainActivity;
import com.minyifang.wcspf.work.ui.home.activities.TakeGoodsActivity;
import com.minyifang.wcspf.work.ui.user.activities.ApplyRefundActivity;
import com.minyifang.wcspf.work.ui.user.activities.CommitCommentActivity;
import com.minyifang.wcspf.work.ui.user.activities.MyCommentActivity;
import com.minyifang.wcspf.work.ui.user.activities.OrderDetailsActivity;
import com.minyifang.wcspf.work.ui.user.activities.RefundDetailsActivity;
import com.minyifang.wcspf.work.ui.user.activities.YaJinDetailsActivity;
import com.minyifang.wcspf.work.ui.user.model.OrderBean;
import com.minyifang.wcspf.work.ui.user.presenter.OrderListPresenter;
import com.minyifang.wcspf.work.ui.user.view.OrderListView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class OrderListFragment extends BaseMvpFragment<OrderListView, OrderListPresenter> implements OrderListView {

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.rv_order_list)
    RecyclerView mRecyclerView;
    @BindView(R.id.ll_empty_view)
    LinearLayout ll_empty_view;

    private String type;
    private int pageIndex = 0;

    private OrderListAdapter mAdapter;
    private List<OrderBean> mList;

    @Override
    protected int setLayoutResource() {
        return R.layout.fragment_order_list;
    }

    @Override
    protected void lazyLoadData() {
        getData();
    }

    private void getData() {
        getPresenter().getOrderList(type, pageIndex);
    }

    @Override
    public void onResume() {
        super.onResume();
        mRefreshLayout.autoRefresh();
    }

    @Override
    protected void initView() {
        Bundle arguments = getArguments();
        if (arguments != null) {
            type = arguments.getString("type");
        }
        mList = new ArrayList<>();
        mAdapter = new OrderListAdapter();
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));


        mRefreshLayout.setOnRefreshListener(refreshLayout -> refreshData());

        mRefreshLayout.setOnLoadMoreListener(refreshLayout -> getData());
    }


    @Override
    protected void initData() {

    }

    @Override
    protected OrderListPresenter createPresenter() {
        return new OrderListPresenter();
    }

    @Override
    public void showLoadingView() {
        showLoadingDialog();
    }

    @Override
    public void hideLoadingView() {
        hideLoadingDialog();
    }

    @Override
    public void onNetworkError() {
        hideLoadingDialog();
        mRefreshLayout.finishRefresh().finishLoadMore();
    }

    @Override
    public void showRequestFailed(String message) {
        mRefreshLayout.finishRefresh().finishLoadMore();
        ToastHelper.getInstance(getContext()).showWarn(message);
    }

    @Override
    public void showOrderList(List<OrderBean> list) {
        mRefreshLayout.finishRefresh().finishLoadMore();
        if (list.size() > 0) {
            pageIndex++;
        }
        mList.addAll(list);
        ll_empty_view.setVisibility(mList.size() > 0 ? View.INVISIBLE : View.VISIBLE);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void showCancelOrderRes(String message) {
        ToastHelper.getInstance(getContext()).showSucceed(message);
        refreshData();
    }

    @Override
    public void showConfirmOrderRes(String message) {
        ToastHelper.getInstance(getContext()).showSucceed(message);
        refreshData();
    }

    @Override
    public void showBuyAgainRes(String message) {
        ToastHelper.getInstance(getActivity()).showSucceed(message);
        LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(new Intent(MainActivity.BROADCAST_CHECK_CART));
        startActivity(new Intent(getActivity(), MainActivity.class));
    }

    @Override
    public void onNoOrderList() {
        ll_empty_view.setVisibility(View.VISIBLE);
    }

    /**
     * 刷新数据
     */
    private void refreshData() {
        mList.clear();
        pageIndex = 0;
        getData();
    }

    class OrderListAdapter extends RecyclerView.Adapter<OrderListAdapter.Holder> {
        @NonNull
        @Override
        public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            Holder holder = new Holder(getLayoutInflater().inflate(R.layout.item_order_list, parent, false));
            return holder;
        }

        @Override
        public void onBindViewHolder(@NonNull Holder holder, int position) {

            OrderBean bean = mList.get(position);
            holder.mTvTakeGoodsType.setText(bean.getWayMode() == 1 ? "门店自提" : "送货上门");
            holder.mTvTakeGoodsType.setBackgroundResource(bean.getWayMode() == 1 ? R.drawable.bg_order_tag_green : R.drawable.bg_order_tag_yellow);
            holder.mTvOrderSn.setText(bean.getNo());
            holder.mTvOrderStatus.setText(bean.getStatus());
            holder.mTvOrderTotalMoney.setText(String.format("￥%s", bean.getPayAmount()));
            holder.mTvGoodsNum.setText(String.format("共%s件", bean.getComNum()));
            holder.mTvOrderTime.setText(bean.getAddTime());

            //0取消订单 1确认支付 2确认收货 3确认提货 4申请退款 5评价订单 6查看评价 7取货二维码 8退货详情 9押金明细 10再来一单
            if (bean.getOperation() != null && !bean.getOperation().trim().isEmpty()) {

                HashSet<String> set = new HashSet<>();
                Collections.addAll(set, bean.getOperation().trim().split(","));
                holder.tvOrderCancel.setVisibility(set.contains("0") ? View.VISIBLE : View.GONE);
                holder.tvOrderPay.setVisibility(set.contains("1") ? View.VISIBLE : View.GONE);
                holder.tvOrderShouHuo.setVisibility(set.contains("2") ? View.VISIBLE : View.GONE);
                holder.tvOrderQuHuo.setVisibility(set.contains("3") ? View.VISIBLE : View.GONE);
                holder.tvOrderTuiKuan.setVisibility(set.contains("4") ? View.VISIBLE : View.GONE);
                holder.tvOrderPjdd.setVisibility(set.contains("5") ? View.VISIBLE : View.GONE);
                holder.tvOrderCkpj.setVisibility(set.contains("6") ? View.VISIBLE : View.GONE);
                holder.tvOrderQuCode.setVisibility(set.contains("7") ? View.VISIBLE : View.GONE);
                holder.tvOrderTuiHuoInfo.setVisibility(set.contains("8") ? View.VISIBLE : View.GONE);
                holder.tvOrderYaJinInfo.setVisibility(set.contains("9") ? View.VISIBLE : View.GONE);
                holder.tvOrderBuy.setVisibility(set.contains("10") ? View.VISIBLE : View.GONE);
            }
            if (!TextUtils.isEmpty(bean.getDeputyPic())) {
                String[] split = bean.getDeputyPic().split(",");
                holder.rvProductPic.setAdapter(new PicAdapter(holder, split));
                holder.rvProductPic.setLayoutManager(new GridLayoutManager(getContext(), 4));
            }

            holder.itemView.setOnClickListener(v -> openOrderDetails(holder.getAdapterPosition()));
            holder.item_view.setOnClickListener(v -> openOrderDetails(holder.getAdapterPosition()));
            holder.tvOrderCancel.setOnClickListener(v -> getPresenter().cancelOrder(bean.getID()));
            holder.tvOrderPay.setOnClickListener(v -> ChoosePayTypeActivity.start(getContext(), bean.getID()));
            holder.tvOrderShouHuo.setOnClickListener(v -> confirmDialog(bean.getID()));
            holder.tvOrderQuHuo.setOnClickListener(v -> confirmDialog(bean.getID()));
            holder.tvOrderTuiKuan.setOnClickListener(v -> ApplyRefundActivity.start(getActivity(), bean.getID()));
            holder.tvOrderPjdd.setOnClickListener(v -> CommitCommentActivity.start(getContext(), bean.getID()));
            holder.tvOrderCkpj.setOnClickListener(v -> startActivity(new Intent(getActivity(), MyCommentActivity.class)));
            holder.tvOrderQuCode.setOnClickListener(v -> startActivity(new Intent(getActivity(), TakeGoodsActivity.class)));
            holder.tvOrderTuiHuoInfo.setOnClickListener(v -> RefundDetailsActivity.start(getActivity(), bean.getID()));
            holder.tvOrderYaJinInfo.setOnClickListener(v -> YaJinDetailsActivity.start(getActivity(), bean.getID()));
            holder.tvOrderBuy.setOnClickListener(v -> getPresenter().buyAgain(bean.getID()));
        }

        public void confirmDialog(String id) {
            new CustomDialog.Builder(getActivity()).setTitle("提示")
                    .setContent("是否确认操作")
                    .setListener(new CustomDialog.OnButtonClickListener() {
                        @Override
                        public void onConfirm(Dialog dialog) {
                            getPresenter().confirmOrder(id);
                            dialog.dismiss();
                        }

                        @Override
                        public void onCancel(Dialog dialog) {
                            dialog.dismiss();
                        }
                    }).build().show();
        }

        @Override
        public int getItemCount() {
            return mList.size();
        }

        public class Holder extends RecyclerView.ViewHolder {

            @BindView(R.id.tv_take_goods_type)
            TextView mTvTakeGoodsType;
            @BindView(R.id.tv_order_sn)
            TextView mTvOrderSn;
            @BindView(R.id.tv_order_status)
            TextView mTvOrderStatus;
            @BindView(R.id.tv_order_total_money)
            TextView mTvOrderTotalMoney;
            @BindView(R.id.tv_goods_num)
            TextView mTvGoodsNum;
            @BindView(R.id.tv_order_time)
            TextView mTvOrderTime;

            @BindView(R.id.item_view)
            View item_view;
            @BindView(R.id.rv_product)
            RecyclerView rvProductPic;  //商品图片列表

            @BindView(R.id.tv_order_cancel)
            TextView tvOrderCancel;
            @BindView(R.id.tv_order_pay)
            TextView tvOrderPay;
            @BindView(R.id.tv_order_shouhuo)
            TextView tvOrderShouHuo;
            @BindView(R.id.tv_order_quhuo)
            TextView tvOrderQuHuo;
            @BindView(R.id.tv_order_tuikuan)
            TextView tvOrderTuiKuan;
            @BindView(R.id.tv_order_pjdd)
            TextView tvOrderPjdd;
            @BindView(R.id.tv_order_ckpj)
            TextView tvOrderCkpj;
            @BindView(R.id.tv_order_qhcode)
            TextView tvOrderQuCode;
            @BindView(R.id.tv_order_tuihuoinfo)
            TextView tvOrderTuiHuoInfo;
            @BindView(R.id.tv_order_yajininfo)
            TextView tvOrderYaJinInfo;
            @BindView(R.id.tv_order_buy)
            TextView tvOrderBuy;

            Holder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }

    class PicAdapter extends RecyclerView.Adapter<PicAdapter.Holder> {
        OrderListAdapter.Holder mHolder;
        String[] mPic;

        public PicAdapter(OrderListAdapter.Holder holder, String[] pic) {
            mHolder = holder;
            mPic = pic;
        }

        @NonNull
        @Override
        public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            Holder holder = new Holder(getLayoutInflater().inflate(R.layout.item_order_list_pic, parent, false));
            holder.itemView.setOnClickListener(v -> openOrderDetails(mHolder.getAdapterPosition()));
            return holder;
        }

        @Override
        public void onBindViewHolder(@NonNull Holder holder, int position) {
            ImageUtils.getInstance().showImage( mPic[position], holder.mIvPicture);
        }

        @Override
        public int getItemCount() {
            return mPic.length > 4 ? 4 : mPic.length;
        }

        public class Holder extends RecyclerView.ViewHolder {
            @BindView(R.id.iv_picture)
            ImageView mIvPicture;

            Holder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }

    private void openOrderDetails(int adapterPosition) {
        OrderDetailsActivity.start(getContext(), mList.get(adapterPosition).getID());
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshEvent(RefreshEvent event) {/* Do something */
        refreshData();
    }
}
